<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>结算商户管理</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
    <style>
        .table th { background-color: #f8f9fa; }
        .merchant-form { max-width: 800px; margin: 0 auto; }
        .channel-link { 
            cursor: pointer; 
            color: #0d6efd;
            margin-right: 5px;
        }
        .channel-link:hover { text-decoration: underline; }
    </style>
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
</head>
<body>
    <div class="container mt-4">
        <h2 class="mb-4">结算商户管理</h2>

        <div class="row mb-4">
            <div class="col">
                <button type="button" class="btn btn-primary" id="addMerchantBtn">
                    添加商户
                </button>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>商户号</th>
                        <th>商户名称</th>
                        <th>默认商户</th>
                        <th>已绑定渠道</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {{#each merchants}}
                    <tr>
                        <td>{{merchant_id}}</td>
                        <td>{{merchant_name}}</td>
                        <td>
                            <div class="form-check">
                                <input class="form-check-input set-default" type="radio" name="defaultMerchant" 
                                    {{#if is_default}}checked{{/if}}
                                    data-id="{{id}}"
                                    data-name="{{merchant_name}}"
                                    id="defaultMerchant{{id}}">
                            </div>
                        </td>
                        <td>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="channel-list-container">
                                    {{#if bound_channels.length}}
                                        {{#each bound_channels}}
                                        <span class="channel-link" 
                                              data-channel-uid="{{uid}}" 
                                              data-merchant-id="{{../id}}"
                                              data-merchant-name="{{../merchant_name}}">
                                            [{{uid}}]{{name}}
                                        </span>
                                        {{#unless @last}}, {{/unless}}
                                        {{/each}}
                                    {{else}}
                                        <span class="text-muted">暂无绑定渠道</span>
                                    {{/if}}
                                </div>
                                <button class="btn btn-sm btn-outline-primary add-channel" 
                                        data-id="{{id}}" 
                                        data-name="{{merchant_name}}">
                                    绑定渠道
                                </button>
                            </div>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-info edit-merchant" data-id="{{id}}">编辑</button>
                        </td>
                    </tr>
                    {{/each}}
                </tbody>
            </table>
        </div>
    </div>

    <!-- 商户表单模态框 -->
    <div class="modal fade" id="merchantModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">商户信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="merchantForm">
                        <input type="hidden" id="merchantId">
                        <div class="mb-3">
                            <label class="form-label">商户号</label>
                            <input type="text" class="form-control" id="merchantNo" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">商户名称</label>
                            <input type="text" class="form-control" id="merchantName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">支付密钥</label>
                            <input type="password" class="form-control" id="paymentKey" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">证书路径</label>
                            <input type="text" class="form-control" id="certPath">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密钥路径</label>
                            <input type="text" class="form-control" id="keyPath">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveMerchant">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 渠道绑定模态框 -->
    <div class="modal fade" id="bindChannelModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">绑定渠道</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="merchantInfoForBinding" class="mb-3"></div>
                    <div class="mb-3">
                        <label for="channelUid" class="form-label">渠道UID</label>
                        <input type="text" class="form-control" id="channelUid" placeholder="请输入渠道用户ID">
                    </div>
                    <div class="alert alert-info">
                        注意：一个渠道只能绑定到一个结算商户。如果渠道已绑定其他商户，需要先解除原有绑定。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmBindChannel">确认绑定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 渠道历史记录模态框 -->
    <div class="modal fade" id="channelHistoryModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">渠道操作历史</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="channelInfo" class="mb-3"></div>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>操作时间</th>
                                    <th>操作类型</th>
                                    <th>操作人</th>
                                </tr>
                            </thead>
                            <tbody id="channelHistoryTableBody"></tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="unbindChannel">解除绑定</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script src="/apps/js/wx-client-dom.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const merchantModal = new bootstrap.Modal(document.getElementById('merchantModal'));
            const bindChannelModal = new bootstrap.Modal(document.getElementById('bindChannelModal'));
            const channelHistoryModal = new bootstrap.Modal(document.getElementById('channelHistoryModal'));
            const apiBasePath = '/apps/loyalty/admin/api/merchant';
            let currentChannelUid = null;
            let currentMerchantId = null;

            // 添加商户按钮点击事件
            document.getElementById('addMerchantBtn').addEventListener('click', function() {
                clearMerchantForm();
                document.getElementById('merchantId').value = '';
                merchantModal.show();
            });

            // 编辑商户按钮点击事件
            document.querySelectorAll('.edit-merchant').forEach(button => {
                button.addEventListener('click', async function() {
                    const merchantId = this.dataset.id;
                    try {
                        const response = await fetch(`${apiBasePath}/${merchantId}`);
                        if (!response.ok) throw new Error('获取商户信息失败');
                        const merchant = await response.json();

                        // 填充表单
                        document.getElementById('merchantId').value = merchant.id;
                        document.getElementById('merchantNo').value = merchant.merchant_id;
                        document.getElementById('merchantName').value = merchant.merchant_name;
                        document.getElementById('paymentKey').value = merchant.payment_key;
                        document.getElementById('certPath').value = merchant.cert_path;
                        document.getElementById('keyPath').value = merchant.key_path;

                        merchantModal.show();
                    } catch (error) {
                        console.error('Error:', error);
                        alert('获取商户信息失败');
                    }
                });
            });

            // 保存商户信息
            document.getElementById('saveMerchant').addEventListener('click', async function() {
                const merchantId = document.getElementById('merchantId').value;
                const data = {
                    merchant_id: document.getElementById('merchantNo').value,
                    merchant_name: document.getElementById('merchantName').value,
                    payment_key: document.getElementById('paymentKey').value,
                    cert_path: document.getElementById('certPath').value,
                    key_path: document.getElementById('keyPath').value
                };

                try {
                    const method = merchantId ? 'PUT' : 'POST';
                    const url = merchantId ? `${apiBasePath}` : `${apiBasePath}`;
                    if (merchantId) data.id = merchantId;

                    const response = await fetch(url, {
                        method: method,
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(data)
                    });

                    if (!response.ok) throw new Error('保存商户信息失败');

                    merchantModal.hide();
                    location.reload();
                } catch (error) {
                    console.error('Error:', error);
                    alert('保存商户信息失败');
                }
            });

            // 清空商户表单
            function clearMerchantForm() {
                document.getElementById('merchantNo').value = '';
                document.getElementById('merchantName').value = '';
                document.getElementById('paymentKey').value = '';
                document.getElementById('certPath').value = '';
                document.getElementById('keyPath').value = '';
            }

            // 设置默认商户
            document.querySelectorAll('.set-default').forEach(radio => {
                radio.addEventListener('change', async function() {
                    const merchantId = this.dataset.id;
                    const merchantName = this.dataset.name;

                    if (!confirm(`确定要将 ${merchantName} 设置为默认结算商户吗？`)) {
                        this.checked = !this.checked;
                        return;
                    }

                    try {
                        const response = await fetch(`${apiBasePath}/${merchantId}/default`, {
                            method: 'PUT'
                        });
                        if (!response.ok) {
                            throw new Error('设置默认商户失败');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('设置默认商户失败');
                        location.reload();
                    }
                });
            });

            // 渠道链接点击事件
            document.querySelectorAll('.channel-link').forEach(link => {
                link.addEventListener('click', async function() {
                    currentChannelUid = this.dataset.channelUid;
                    currentMerchantId = this.dataset.merchantId;
                    const merchantName = this.dataset.merchantName;
                    await loadChannelHistory(currentChannelUid, currentMerchantId);
                    channelHistoryModal.show();
                });
            });

            // 绑定渠道按钮点击事件
            document.querySelectorAll('.add-channel').forEach(button => {
                button.addEventListener('click', function() {
                    currentMerchantId = this.dataset.id;
                    document.getElementById('merchantInfoForBinding').innerHTML = `
                        <strong>商户名称：</strong>${this.dataset.name}
                    `;
                    document.getElementById('channelUid').value = '';
                    bindChannelModal.show();
                });
            });

            // 确认绑定渠道
            document.getElementById('confirmBindChannel').addEventListener('click', async function() {
                const channelUid = document.getElementById('channelUid').value.trim();
                if (!channelUid) {
                    alert('请输入渠道UID');
                    return;
                }

                try {
                    const response = await fetch(`${apiBasePath}/${currentMerchantId}/channel/${channelUid}`, {
                        method: 'POST'
                    });

                    if (response.ok) {
                        bindChannelModal.hide();
                        location.reload();
                    } else {
                        const error = await response.json();
                        alert('绑定失败: ' + error.error);
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('绑定失败');
                }
            });

            // 解除绑定
            document.getElementById('unbindChannel').addEventListener('click', async function() {
                if (!confirm('确定要解除此渠道的绑定吗？')) {
                    return;
                }

                try {
                    const response = await fetch(`${apiBasePath}/${currentMerchantId}/channel/${currentChannelUid}`, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        channelHistoryModal.hide();
                        location.reload();
                    } else {
                        const error = await response.json();
                        alert('解除绑定失败: ' + error.error);
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('解除绑定失败');
                }
            });

            // 加载渠道历史记录
            async function loadChannelHistory(channelUid, merchantId) {
                try {
                    const response = await fetch(`${apiBasePath}/${merchantId}/channel/${channelUid}/history`);
                    const data = await response.json();

                    document.getElementById('channelInfo').innerHTML = `
                        <strong>渠道信息：</strong>[${data.channel.uid}] ${data.channel.real_name} 
                        ${data.channel.agency ? `(${data.channel.agency})` : ''}
                    `;

                    const tableBody = document.getElementById('channelHistoryTableBody');
                    tableBody.innerHTML = '';

                    data.history.forEach(record => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${record.created_at}</td>
                            <td>${record.operation_type === 'bind' ? '绑定' : '解绑'}</td>
                            <td>${record.operator_name}</td>
                        `;
                        tableBody.appendChild(row);
                    });

                    // 根据当前绑定状态显示/隐藏解绑按钮
                    document.getElementById('unbindChannel').style.display = 
                        data.is_bound ? 'block' : 'none';
                } catch (error) {
                    console.error('Error:', error);
                    alert('加载渠道历史记录失败');
                }
            }

            // 保持其他现有代码不变...
        });
    </script>
</body>
</html> 
